<template>
  <view class="home-container">
    <!-- 问卷列表 -->
    <view class="questionnaire-list">
      <!-- 有问卷时显示列表 -->
      <template v-if="questionnaires.length > 0">
        <view 
          v-for="(item, index) in questionnaires" 
          :key="index" 
          class="questionnaire-card"
          @click="handleCardClick(item)"
          :style="{ 
            '--delay': index * 0.3 + 's',
            'pointer-events': allowInteraction ? 'auto' : 'none'
          }"
          @mouseover="handleHover(index)"
          @mouseleave="handleLeave(index)"
        >
          <!-- 彩色装饰条 -->
          <view class="card-accent" :style="{ 'background': item.color }"></view>
          <!-- 卡片内容 -->
          <view class="card-content">
            <text class="card-title">{{ item.title }}</text>
            <text class="card-desc">{{ item.desc }}</text>
            <view class="card-meta">
              <uni-icons type="info" size="16" color="#7c8dad"></uni-icons>
              <text>约{{ item.estimateTime }}分钟</text>
            </view>
          </view>
          <view class="card-arrow">
            <uni-icons type="eye" size="30" color="#7c8dad"></uni-icons>
          </view>
          <!-- 悬浮覆盖层 -->
          <view class="card-hover-overlay" :class="{ 'active': activeIndex === index }"></view>
        </view>
      </template>
      
      <!-- 无问卷时显示空状态 -->
      <view v-else class="empty-state">
        <image src="/static/images/empty.png" mode="aspectFit" class="empty-image"/>
        <text class="empty-text">{{ emptyText }}</text>
        <text class="empty-subtext">{{ emptySubtext }}</text>
      </view>
    </view>

    <!-- 问卷弹窗组件 -->
    <questionnaire 
      :visible="showQuestionnaire" 
      @update:visible="val => showQuestionnaire = val"
      :questionnaireId="questionnaireId"
      @submit="handleAssessmentResult"
    />
  </view>
</template>

<script>
import questionnaire from '@/component/questionnaire.vue'
import uniIcons from "@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue"
import methodY from "@/util/methodY.js"
import { QUESTIONNAIRE_SETS } from "@/data/data.js"

export default {
  components: {
    questionnaire,
    uniIcons
  },
  data() {
    return {
      showQuestionnaire: false,
      questionnaireId: 0,
      user: null,
      allowInteraction: false,
      questionnaires: [],
      activeIndex: -1,
      emptyText: "暂时没有待填写的问卷",
      emptySubtext: "您已完成所有问卷或暂无新问卷",
      isLoading: false,
      colorPool: [
        '#3366FF', '#FF3333', '#00CC66', '#FF9933', '#9933FF', 
        '#00CCCC', '#FF6699', '#6600CC', '#FFCC00', '#006633',
        '#FF0066', '#0044CC', '#00994C', '#FF6600', '#660099',
        '#008080', '#CC0000', '#FF9900'
      ],
      usedColors: new Set()
    }
  },
  methods: {
    // 获取唯一颜色（不重复直到颜色池用尽）
    getUniqueColor() {
      // 颜色池用尽时重置
      if (this.usedColors.size >= this.colorPool.length) {
        this.usedColors.clear()
      }

      // 筛选未使用颜色
      const availableColors = this.colorPool.filter(
        color => !this.usedColors.has(color)
      )

      // 随机选择并标记为已用
      const selectedColor = availableColors[
        Math.floor(Math.random() * availableColors.length)
      ]
      this.usedColors.add(selectedColor)
      return selectedColor
    },

    // 重置颜色池
    resetColorPool() {
      this.usedColors.clear()
    },

    handleHover(index) {
      this.activeIndex = index
    },
    
    handleLeave(index) {
      this.activeIndex = -1
    },
    
    handleCardClick(item) {
      if (!this.allowInteraction) return
      this.openQuestionnaire(item)
    },
    
    openQuestionnaire(item) {
      this.questionnaireId = item.id
      this.showQuestionnaire = true
    },
    
    async handleAssessmentResult(result) {
      methodY.util.showLoading("结果分析中……")
      const user = methodY.util.getUserInfo()
      try {
        await methodY.util.sendQuestionnaireRecord(
          result.questionnaireId, 
          user.userId, 
          result.totalScore
        )
        uni.showModal({
          title: `评估完成 - ${result.questionnaireTitle}`,
          content: `您的总分: ${result.totalScore}\n评估结果: ${result.assessment}`,
          showCancel: false
        })
        this.showQuestionnaires()
      } catch (e) {
        console.error('提交失败:', e)
        methodY.util.showMsg("提交失败，请重试", 2000)
      } finally {
        methodY.util.closeLoading()  
      }
    },
    
    async showQuestionnaires() {
      if (this.isLoading) return
      
      this.isLoading = true
      this.resetColorPool() // 重置颜色使用记录
      this.emptyText = "加载中..."
      this.emptySubtext = ""
      methodY.util.showLoading("加载中...")
      
      try {
        const apiResponse = await methodY.util.getUserQuestionnaireRecord(this.user.userId)
        const completedRecords = apiResponse.data || apiResponse
        
        if (!Array.isArray(completedRecords)) {
          throw new Error('API返回数据格式不正确')
        }
        
        const completedIds = completedRecords.map(item => item.questionnaireId)
        this.questionnaires = QUESTIONNAIRE_SETS
          .filter(q => !completedIds.includes(q.id))
          .map(item => ({
            ...item,
            color: this.getUniqueColor() // 分配唯一颜色
          }))
          
        if (this.questionnaires.length === 0) {
          this.emptyText = "暂时没有待填写的问卷"
          this.emptySubtext = "您已完成所有问卷或暂无新问卷"
        }
        
      } catch (error) {
        console.error('加载问卷失败:', error)
        this.questionnaires = []
        this.emptyText = "加载问卷失败"
        this.emptySubtext = "请检查网络连接后重试"
        methodY.util.showMsg("加载问卷失败", 2000)
      } finally {
        this.isLoading = false
        methodY.util.closeLoading()
        this.allowInteraction = true
      }
    }
  },
  mounted() {
    setTimeout(() => {
      this.allowInteraction = true
    }, 500 + (this.questionnaires.length * 100))
  },
  created() {
    this.user = methodY.util.getUserInfo()
    this.showQuestionnaires()
  }
}
</script>

<style lang="scss" scoped>
.home-container {
  padding: 20px;
  min-height: 100vh;
  background: #f5f7fa;
}

.questionnaire-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.questionnaire-card {
  position: relative;
  display: flex;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.1);
  transform: translateY(20px);
  opacity: 0;
  animation: fadeInUp 0.6s forwards;
  animation-delay: var(--delay);
  cursor: pointer;
  
  &:hover {
    transform: translateY(-4px) scale(1.01);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
    
    .card-accent {
      width: 100%;
      opacity: 0.15;
    }
    
    .card-title {
      color: #2c3e50;
    }
    
    .card-arrow {
      transform: translateX(4px);
    }
  }
}

.card-accent {
  position: absolute;
  top: 0;
  left: 0;
  width: 6px;
  height: 100%;
  transition: all 1s cubic-bezier(0.175, 0.885, 0.32, 1.1);
}

.card-hover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(255,255,255,0.3) 0%, rgba(255,255,255,0) 100%);
  opacity: 0;
  transition: opacity 0.1s ease;
  
  &.active {
    opacity: 1;
  }
}

.card-content {
  flex: 1;
  padding: 20px;
  z-index: 1;
}

.card-title {
  display: block;
  font-size: 18px;
  font-weight: 600;
  color: #34495e;
  margin-bottom: 8px;
  transition: color 0.3s ease;
}

.card-desc {
  display: block;
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 12px;
  line-height: 1.5;
}

.card-meta {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #7c8dad;
  
  uni-icons {
    margin-right: 6px;
  }
}

.card-arrow {
  display: flex;
  align-items: center;
  padding: 0 20px;
  transition: transform 0.3s ease;
  z-index: 1;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  text-align: center;
}

.empty-image {
  width: 180px;
  height: 180px;
  margin-bottom: 20px;
  opacity: 0.8;
}

.empty-text {
  font-size: 16px;
  color: #34495e;
  margin-bottom: 8px;
  font-weight: 500;
}

.empty-subtext {
  font-size: 14px;
  color: #95a5a6;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>